package net.shippo.poc.azure.iothub.amqps;

import java.io.IOException;
import java.net.URISyntaxException;

import com.microsoft.azure.iot.service.sdk.DeliveryAcknowledgement;
import com.microsoft.azure.iot.service.sdk.FeedbackBatch;
import com.microsoft.azure.iot.service.sdk.FeedbackReceiver;
import com.microsoft.azure.iot.service.sdk.IotHubServiceClientProtocol;
import com.microsoft.azure.iot.service.sdk.Message;
import com.microsoft.azure.iot.service.sdk.ServiceClient;

public class SendMsgToDeviceService {
	private static final String connectionString = "HostName=iot-poc-hub.azure-devices.cn;SharedAccessKeyName=service;SharedAccessKey=tK/J2xRfJIjqyh8jk5rrN7yVH9AoPDQEb1UPrWjYJNE=";
	private static final String deviceId = "myFirstJavaDevice";
	private static final IotHubServiceClientProtocol protocol = IotHubServiceClientProtocol.AMQPS;

	public static void main(String[] args) throws IOException, URISyntaxException, Exception {
		ServiceClient serviceClient = ServiceClient.createFromConnectionString(connectionString, protocol);

		if (serviceClient != null) {
			serviceClient.open();
			FeedbackReceiver feedbackReceiver = serviceClient.getFeedbackReceiver(deviceId);
			if (feedbackReceiver != null)
				feedbackReceiver.open();

			Message messageToSend = new Message("Cloud to device message.");
			messageToSend.setDeliveryAcknowledgement(DeliveryAcknowledgement.Full);

			serviceClient.send(deviceId, messageToSend);
			System.out.println("Message sent to device");

			FeedbackBatch feedbackBatch = feedbackReceiver.receive(10000);
			if (feedbackBatch != null) {
				System.out.println(
						"Message feedback received, feedback time: " + feedbackBatch.getEnqueuedTimeUtc().toString());
			}

			if (feedbackReceiver != null)
				feedbackReceiver.close();
			serviceClient.close();
		}
	}
}
